﻿using UnityEngine;
using System.Collections;

public class TouchPoint : MonoBehaviour {

    static TouchPoint Instance;

    static public void CreateTouchPoint()
    {
        if (Instance == null)
        {
            GameObject prefab = Resources.Load("Prefabs/TouchPoint/TouchPointCamera") as GameObject;
            GameObject obj = Instantiate(prefab) as GameObject;
            Instance = obj.GetComponent<TouchPoint>();

            DontDestroyOnLoad(obj);
        }
    }

    Vector3 DownPos;
    public Animator m_TouchAni;
    bool isDrag = false;
    bool isDown = false;

    const float dragStandard = 15.0f;
	
	// Update is called once per frame
	void Update ()
    {
        if (!CSceneManager.IsIngameScene())
        {
            if (Input.GetMouseButtonDown(0))
            {
                isDown = true;
                isDrag = false;
                DownPos = Input.mousePosition;
            }

            if (isDown && !isDrag)
            {
                if (Input.GetMouseButton(0))
                {
                    if (DistanceOfTowPos(Input.mousePosition, DownPos) > dragStandard)
                        isDrag = true;
                }
            }

            if (Input.GetMouseButtonUp(0))
            {
                if (!isDrag)
                {
                    camera.enabled = true;
                    m_TouchAni.transform.position = camera.ScreenToWorldPoint(Input.mousePosition);
                    m_TouchAni.gameObject.SetActive(false);
                    m_TouchAni.gameObject.SetActive(true);

                    StopCoroutine("HideObj");
                    StartCoroutine("HideObj", m_TouchAni.gameObject);
                }
                isDown = false;
                isDrag = false;
            }
        }        
	}

    IEnumerator HideObj(GameObject obj)
    {
        yield return new WaitForSeconds(1.0f);
        obj.SetActive(false);
        camera.enabled = false;
    }

    float DistanceOfTowPos(Vector3 a, Vector3 b)
    {
        float x = a.x - b.x;
        float y = a.y - b.y;

        return Mathf.Sqrt((x * x) + (y * y));
    }
}
